from rest_framework.generics import ListAPIView
from rest_framework.viewsets import ModelViewSet
from .good_serializers import SkuViewSetSerializer, SkuCategoriesModelSerializers, GoodSimpleModelSerializers, GoodsIdSpecModelSerializers
from goods.models import SKU, GoodsCategory, SPU, SPUSpecification
from meiduo_admin.utils import MyPageNumberPagination


class SkuViewSet(ModelViewSet):
    serializer_class = SkuViewSetSerializer
    # queryset = SKU.objects.order_by("id").all()
    pagination_class = MyPageNumberPagination

    # 商品查询过滤操作(根据商品名称模糊查询)
    # 重写数据源
    def get_queryset(self):
        # 获取查询关键字
        keyword = self.request.query_params.get("keyword")
        # 根据关键字进行判断查询
        if keyword:     # 有要查询的数据则返回对应数据
            return SKU.objects.filter(name__contains=keyword).order_by("id").all()
        else:       # 否则返回全部数据
            return SKU.objects.order_by("id").all()


class SkuCategoriesView(ListAPIView):
    serializer_class = SkuCategoriesModelSerializers
    queryset = GoodsCategory.objects.filter(subs=None).all()


class GoodSimpleView(ListAPIView):
    serializer_class = GoodSimpleModelSerializers
    queryset = SPU.objects.all()


class GoodsIdSpecView(ListAPIView):
    serializer_class = GoodsIdSpecModelSerializers
    # queryset = SPUSpecification.objects.all()

    # 判断传过来的spu_id,分别显示对应的商品规格选项
    # 重写数据源
    def get_queryset(self):
        # 获取路由中正则匹配的参数spu_id
        return SPUSpecification.objects.filter(spu_id=self.kwargs.get("spu_id")).all()
